package com.yuke.cloud.service.wmc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillDto;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillSkuDto;
import com.yuke.cloud.service.api.pmc.dto.ProdCategoryDto;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoExDto;
import com.yuke.cloud.service.api.pmc.dto.ProdStorageDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.wmc.dto.StorageDto;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.api.wmc.dto.WareProductDto;
import com.yuke.cloud.service.wmc.dao.WmsStorageMapper;
import com.yuke.cloud.service.wmc.dto.WmsStatisticsDto;
import com.yuke.cloud.service.wmc.dto.WmsStorageDto;
import com.yuke.cloud.service.wmc.dto.WmsStoragePicDto;
import com.yuke.cloud.service.wmc.dto.WmsStorageProdDto;
import com.yuke.cloud.service.wmc.entity.WmsStorage;
import com.yuke.cloud.service.wmc.service.WmsStorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;


/**
 * Created by zys on 2018/11/26.
 */
@Service
@Transactional
public class WmsStorageServiceImpl extends BaseService<WmsStorage> implements WmsStorageService {
    @Resource
    private WmsStorageMapper wmsStorageMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private PmcFeignApi pmcFeignApi;

    @Override
    public List<WmsStorage> getStorageNum(List<StorageDto> dto) {
        return wmsStorageMapper.getStorageNum(dto);
    }


    @Override
    @Async
    public CompletableFuture<Integer> addGoodsStorage(ProdStorageDto prodStorageDto,List<ProdSpecInfoExDto> prodSpecInfoExDtoList) {


        //获得当前产品在库存中的信息
        WmsStorage wmsStorage = new WmsStorage();
        wmsStorage.setProductId(prodStorageDto.getProductId());
        wmsStorage.setWarehouseId(prodStorageDto.getWarehouseId());
        List<WmsStorage> wmsStorageList = new ArrayList<>();
        wmsStorageList = this.select(wmsStorage);

        if (wmsStorageList == null || wmsStorageList.size()<1){ //库存中没有该产品

            for (ProdSpecInfoExDto prodSpecInfoExDto : prodSpecInfoExDtoList) {
                WmsStorage ws = new WmsStorage();
                BeanUtils.copyProperties(prodSpecInfoExDto,ws);
                ws.setWarehouseId(prodStorageDto.getWarehouseId());
                ws.setUpdateId(prodStorageDto.getUpdateId());
                wmsStorageList.add(ws);
            }
            //新增库存信息
            this.batchSave(wmsStorageList);
        }else {//有该产品

            for (ProdSpecInfoExDto prodSpecInfoExDto : prodSpecInfoExDtoList) {
                boolean ifcontain = false;
                for (WmsStorage item : wmsStorageList){
                    if (prodSpecInfoExDto.getSpecId().equals(item.getSpecId()) && item.getWarehouseId().equals(prodStorageDto.getWarehouseId())){
                        //当有相同规格specId，即以前入过库，修改信息
                        WmsStorage wss = new WmsStorage();
                        //BeanUtils.copyProperties(item,wss);
                        wss.setStorageId(item.getStorageId());
                        wss.setWarehouseId(item.getWarehouseId());
                        wss.setSpecId(prodSpecInfoExDto.getSpecId());
                        wss.setProductId(prodSpecInfoExDto.getProductId());
                        wss.setCategoryId(prodSpecInfoExDto.getCategoryId());
                        wss.setBrandId(prodSpecInfoExDto.getBrandId());
                        wss.setSpecName(prodSpecInfoExDto.getSpecName());
                        wss.setUpdateId(prodStorageDto.getUpdateId());
                        if (item.getQuality().equals(0) && prodSpecInfoExDto.getQuality() != null && prodSpecInfoExDto.getQuality() != 0){
                            wss.setQuality(prodSpecInfoExDto.getQuality());
                        }
                        this.update(wss);
                        System.out.println("更新："+wss);
                        ifcontain = true;
                        break;
                    }
                }
                if (ifcontain){
                    continue;
                }else{//当没有相同规格specId，即以前没有入库，插入信息
                    WmsStorage ws = new WmsStorage();
                    BeanUtils.copyProperties(prodSpecInfoExDto,ws);
                    ws.setWarehouseId(prodStorageDto.getWarehouseId());
                    ws.setUpdateId(prodStorageDto.getUpdateId());
                    ws.setMarketPrice(prodStorageDto.getMarketPrice());
                    ws.setStockPrice(prodStorageDto.getStockPrice());
                    ws.setGuidancePrice(prodStorageDto.getGuidancePrice());
                    this.save(ws);
                    System.out.println("新增："+ws);
                }

            }

        }
        return  CompletableFuture.completedFuture(1);
    }

    @Override
    public void updatewarehousestorageznum(Long transferWarehouseId, Long transferSpecId, Integer transferNum) {
        wmsStorageMapper.updatewarehousestorageznum(transferWarehouseId,transferSpecId,transferNum);
    }

    @Override
    public void updatewarehousestoragefnum(Long beTransferedWarehouseId, Long transferSpecId, int i) {
        wmsStorageMapper.updatewarehousestoragefnum(beTransferedWarehouseId,transferSpecId,i);
    }

    @Override
    public Map<Long, Integer> getCityStockCount(List<Long> specIds, Long regionCityId) {
        Map<Long, Integer> stockCountMap = new HashMap<Long, Integer>();

        if (specIds != null && specIds.size() > 0) {
            List<Map<String, Object>> stockCounts = wmsStorageMapper.getCityStockCount(specIds, regionCityId);

            for (Long specId : specIds) {
                stockCountMap.put(specId, 0);
                for (int i = 0; i < stockCounts.size(); i++) {
                    if (specId.equals(Long.valueOf(stockCounts.get(i).get("spec_id").toString()))) {
                        stockCountMap.put(specId, Integer.valueOf(stockCounts.get(i).get("stock_count").toString()));
                        break;
                    }
                }
            }
        }
        return stockCountMap;
    }

    @Override
    public Map<Long, Integer> getCityAllStockCount(Long regionCityId) {
        Map<Long, Integer> stockCountMap = new HashMap<Long, Integer>();
        List <Map<String, Object>> stockCounts = wmsStorageMapper.getCityAllStockCount(regionCityId);

        for (int i = 0; i < stockCounts.size(); i++) {
            stockCountMap.put(Long.valueOf(stockCounts.get(i).get("spec_id").toString()), Integer.valueOf(stockCounts.get(i).get("stock_count").toString()));
        }
        return stockCountMap;
    }

    @Override
    public void updateWarehouseStorage(Long warehouseId, Long specId, Integer number, Integer lockNumber) {
        wmsStorageMapper.updateWarehouseStorage(warehouseId, specId, number, lockNumber);
    }

	@Override
	public void updateStorageData(Long warehouseId, Long specId, Integer number, Integer purchasePrice, Integer quality) {
        wmsStorageMapper.updateStorageData(warehouseId, specId, number, purchasePrice,quality);
    }

    // 获取正在秒杀活动中的商品
    @Override
    public List<CmsSecKillSkuDto> getSecKillSkus() {
        Set<String> keys = redisTemplate.keys(RedisKeyUtil.getSecKillKeys());

        if (CollectionUtils.isEmpty(keys)) {
            return new ArrayList<>();
        }

        List<CmsSecKillSkuDto> cmsSecKillSkuDtoList = new ArrayList<>();
        Date now = new Date();
        for (String secKillKey : keys) {
            CmsSecKillDto cmsSecKillDto = (CmsSecKillDto)redisTemplate.opsForValue().get(secKillKey);
            if (cmsSecKillDto != null && cmsSecKillDto.getIsEnable() && now.getTime() >= cmsSecKillDto.getStartTime().getTime()
                    && now.getTime() <= cmsSecKillDto.getEndTime().getTime()) {
                Set<String> skuKeys = redisTemplate.keys(RedisKeyUtil.getSecKillSkuKeys(String.valueOf(cmsSecKillDto.getSecKillId())));

                for (String skuKey : skuKeys) {
                    CmsSecKillSkuDto cmsSecKillSkuDto = (CmsSecKillSkuDto)redisTemplate.opsForValue().get(skuKey);
                    if (cmsSecKillSkuDto != null) {
                        cmsSecKillSkuDtoList.add(cmsSecKillSkuDto);
                    }
                }
            }
        }

        return cmsSecKillSkuDtoList;
    }

    @Override
    public List<WareProductDto> getRemoteStockCount(List<Long> specIds, Long localWarehouseId) {
        if (specIds != null && specIds.size() > 0) {
            return wmsStorageMapper.getRemoteStockCount(specIds, localWarehouseId);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public Map<Long, Integer> getWarehouseStockCount(Long warehouseId, List<Long> specIds) {
        Map<Long, Integer> stockCountMap = new HashMap<Long, Integer>();

        if (specIds != null && specIds.size() > 0) {
            List<Map<String, Object>> stockCounts = wmsStorageMapper.getWarehouseStockCount(warehouseId, specIds);

            for (Long specId : specIds) {
                stockCountMap.put(specId, 0);
                for (int i = 0; i < stockCounts.size(); i++) {
                    if (specId.equals(Long.valueOf(stockCounts.get(i).get("spec_id").toString()))) {
                        stockCountMap.put(specId, Integer.valueOf(stockCounts.get(i).get("stock_count").toString()));
                        break;
                    }
                }
            }
        }
        return stockCountMap;
    }

    @Override
    public List<WmsStorage> getStorageInfo() {
        return wmsStorageMapper.getStorageInfo();
    }

    @Override
    public void updateByStorageDtos(List<StorageDto> storageDtos){
        wmsStorageMapper.updateByStorageDtos(storageDtos);
    }


    @Override
    public void addGoodsStorage(List<WmsStorageDto> list) {
        wmsStorageMapper.addGoodsStorage(list);
    }

    @Override
    public  List<WmsStorageProdDto>  getStorageSpec(WmsStorageProdDto wmsStorageProdDto) {
        List<WmsStorageProdDto> storageSpec = wmsStorageMapper.getStorageSpec(wmsStorageProdDto);
        return storageSpec;
    }

    @Override
    public List<WmsStorage> getWmsStorageByPic(WmsStoragePicDto wmsStoragePicDto) {
        List<WmsStorage> wmsStorageByPic = wmsStorageMapper.getWmsStorageByPic(wmsStoragePicDto);
        return wmsStorageByPic;
    }

    @Override
    public List<WareProductDto> getInfoWarehouseIds(List<Long> specIds) {
        List<WareProductDto> infoWarehouseIds = wmsStorageMapper.getInfoWarehouseIds(specIds);
        return infoWarehouseIds;
    }

    @Override
    public List<StorageSpecInfoDto> getWmsSpecInfoBySpecIds(Long warehouseId,List<Long> specIds){
        return  wmsStorageMapper.getStorageInfoBySpecIds(specIds,warehouseId);
    }

    @Override
    public List<WmsStorage> getWmsStorageByCondition(WmsStoragePicDto wmsStoragePicDto) {
        ////大于等于
        //if (beginNumber != null && !beginNumber.equals("")) {
        //    wmsStoragePicDto.setBeginNumber(beginNumber);
        //}
        ////小于等于
        //if (endNumber != null && !endNumber.equals("")) {
        //    wmsStoragePicDto.setEndNumber(endNumber);
        //}
        //if (specId != null && !specId.equals("")) {
        //    wmsStoragePicDto.setSpecId(specId);
        //}
        //if (categoryId != null && !categoryId.equals("")) {
        //    wmsStoragePicDto.setCategoryId(categoryId);
        //}
        //
        //if (qualityAlert != null && !qualityAlert.equals("") && !qualityAlert.equals(0)) {
        //    wmsStoragePicDto.setQualityAlert(qualityAlert);
        //}
        //
        //if (stockinAlert != null && !stockinAlert.equals("") && !stockinAlert.equals(0)) {
        //    wmsStoragePicDto.setStockinAlert(stockinAlert);
        //}
        //

        List<WmsStorage> wmsStorage = wmsStorageMapper.getWmsStorageByCondition(wmsStoragePicDto);
        return wmsStorage;
    }


    @Override
    public List<StorageDto> getStorageInfoByStorageId(List<Long> storageIds){
        return wmsStorageMapper.getStorageInfoByStorageId(storageIds);
    }

      @Override
        public PageInfo<WmsStatisticsDto> storageAndUnitPrice(WmsStatisticsDto wmsStatisticsDto,Integer page,Integer size) {

            if (wmsStatisticsDto.getParentId()!=null&&!wmsStatisticsDto.getParentId().equals((byte)0)){
                ProdCategoryDto prodCategoryDto = new ProdCategoryDto();
                prodCategoryDto.setParentId(wmsStatisticsDto.getParentId());
                prodCategoryDto.setCategoryId(wmsStatisticsDto.getParentId());
                List<Long> list = pmcFeignApi.findLeaf(prodCategoryDto);
                wmsStatisticsDto.setCategoryIdList(list);
                wmsStatisticsDto.setCategoryId(null);
            }

            PageHelper.startPage(page,size);

            List<WmsStatisticsDto> list = wmsStorageMapper.storageAndUnitPrice(wmsStatisticsDto);

            PageInfo pageInfo = new PageInfo(list);

            return pageInfo;
        }





}
